<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>menu</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <style>
        .layui-btn:not(.layui-btn-lg):not(.layui-btn-sm):not(.layui-btn-xs) {
            height: 34px;
            line-height: 34px;
            padding: 0 8px;
        }
    </style>
</head>

<body>
    <div class="layuimini-container">
        <div class="layuimini-main">
            <div>
                <div class="layui-btn-group">
                    <button class="layui-btn layui-btn-normal" id="btn-refresh-gather-info">刷新设备信息</button>
                    <button class="layui-btn layui-btn-normal" id="btn-set-gather-task">批量设置采集任务</button>
                    <button class="layui-btn layui-btn-normal" id="btn-set-gather-type">设置选中设备类目</button>
                    <button class="layui-btn layui-btn-normal" id="btn-set-gather-notes">批量备注</button>
                </div>
                <div class="layui-btn-group">
                    <button class="layui-btn" id="btn-expand">全部展开</button>
                    <button class="layui-btn" id="btn-fold">全部折叠</button>
                </div>
                <table id="munu-table" class="layui-table" lay-filter="munu-table"></table>
            </div>
        </div>
    </div>
    <!-- 操作列 -->
    <script type="text/html" id="auth-state">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="startGatherTask">开始任务</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="stopGatherTask">停止任务</a>
    </script>

    <script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
    <script src="../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
    <script>

        var g_selectDevices
        var renderTable

        layui.use(['table', 'treetable'], function () {
            var $ = layui.jquery;
            var table = layui.table;
            var treetable = layui.treetable;

            // 渲染表格
            renderTable = function () {
                layer.load(2);  //加载层
                treetable.render({
                    treeColIndex: 1,
                    treeSpid: -1,
                    treeIdName: 'authorityId',
                    treePidName: 'parentId',
                    elem: '#munu-table',
                    url: '/api/gather/getDevices',
                    page: false,
                    cols: [[
                        { type: 'checkbox' }, // 添加勾选框列
                        { field: 'deviceName', width: 160, title: '设备名称' },
                        { field: 'accountNickName', width: 160, title: '昵称' },
                        { field: 'accountId', width: 160, title: '逛逛号' },
                        { field: 'gatherTitleNum', width: 160, align: 'center', title: '已经采集标题数量' },
                        { field: 'accountType', width: 100, align: 'center', title: '所属类目' },
                        { field: 'accountRemarks', width: 100, align: 'center', title: '备注' },
                        { field: 'accountStatus', width: 100, align: 'center', title: '状态' },
                        { templet: '#auth-state', minWidth: 120, align: 'center', title: '操作' }
                    ]],
                    done: function () {
                        layer.closeAll('loading');
                    }
                });
            };
            renderTable();

            $('#btn-expand').click(function () {
                treetable.expandAll('#munu-table');
            });

            $('#btn-fold').click(function () {
                treetable.foldAll('#munu-table');
            });

            $('#btn-refresh-gather-info').click(function () {
                renderTable()
                layer.msg('刷新选中设备信息成功');
            });

            $('#btn-set-gather-task').click(function () {
                checkStatusData = table.checkStatus('munu-table').data
                g_selectDevices = JSON.stringify(checkStatusData)

                let setGatherTaskPop = layer.open({
                    title: '批量设置采集任务',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['80%', '80%'],
                    content: '../page/table/setGatherTask.html',
                });
            });

            $('#btn-set-gather-type').click(function () {
                checkStatusData = table.checkStatus('munu-table').data
                g_selectDevices = JSON.stringify(checkStatusData)

                let setDeviceTypePop = layer.open({
                    title: '批量设置类目',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['40%', '50%'],
                    content: '../page/table/setGatherType.html',
                })
            })

            $('#btn-set-gather-notes').click(function () {
                checkStatusData = table.checkStatus('munu-table').data
                g_selectDevices = JSON.stringify(checkStatusData)

                let setDeviceTypePop = layer.open({
                    title: '批量备注',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['40%', '25%'],
                    content: '../page/table/setGatherNotes.html',
                })
            })

            function delay(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            }

            //监听工具条
            table.on('tool(munu-table)', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;

                if (layEvent === 'startGatherTask') {
                    if (data.parentId === -1) {
                        layer.msg('请选择账号执行任务');
                        return;
                    }

                    if (data.accountStatus != '正常') {
                        layer.msg('设备状态异常，无法开始采集任务');
                        return;
                    }

                    if (data.accountType == '') {
                        layer.msg('请先设置设备所属类目');
                        return;
                    }

                    let taskInfo = JSON.parse(localStorage.getItem('gatherTask'))

                    let accountInfoList = taskInfo[data.parentId]

                    let targetAccountInfo = null

                    for (let i = 0; i < accountInfoList.length; i++) {
                        let accountInfo = accountInfoList[i]
                        if (accountInfo.accountId === data.accountId) {
                            targetAccountInfo = accountInfo
                            isFound = true
                            break
                        }
                    }

                    if (targetAccountInfo === null) {
                        layer.msg('请先给该账号设置采集任务');
                        return;
                    }

                    let accountInfo = {
                        deviceName: data.deviceName,
                        accountNickName: data.accountNickName,
                        accountId: data.accountId,
                        gatherTitleNum: data.gatherTitleNum,
                        accountType: data.accountType,
                        accountStatus: data.accountStatus,
                        accountRemarks: data.accountRemarks
                    }

                    let taskParams = {
                        commissionRate: targetAccountInfo.commissionRate,
                        gatherLimit: targetAccountInfo.gatherLimit,
                        keyWordList: targetAccountInfo.keyWordList
                    }

                    let postData = {
                        parentId: data.parentId,
                        accountInfo: accountInfo,
                        taskParams: taskParams
                    }

                    $.ajax({
                        url: '/api/gather/accountStartTask', // API 地址
                        method: 'POST', // 请求方法
                        contentType: 'application/json', // 请求内容类型
                        data: JSON.stringify(postData), // 将数据转换为 JSON 字符串
                        success: function (response) {
                            // 处理成功的响应
                            var iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);
                            parent.renderTable()
                        },
                        error: function (xhr, status, error) {
                            // 处理错误响应
                            console.error('编辑类目失败:', xhr.responseJSON);
                            // 可以在这里显示错误提示
                            layer.msg(`编辑类目失败，${xhr.responseJSON.message}`);
                        }
                    });

                    layer.msg('开始任务 ' + data.deviceName);
                } else if (layEvent === 'stopGatherTask') {

                    let accountInfo = {
                        deviceName: data.deviceName,
                        accountNickName: data.accountNickName,
                        accountId: data.accountId,
                        gatherTitleNum: data.gatherTitleNum,
                        accountType: data.accountType
                    }

                    let postData = {
                        parentId: data.parentId,
                        accountInfo: accountInfo
                    }

                    $.ajax({
                        url: '/api/gather/accountStopTask', // API 地址
                        method: 'POST', // 请求方法
                        contentType: 'application/json', // 请求内容类型
                        data: JSON.stringify(postData), // 将数据转换为 JSON 字符串
                        success: function (response) {
                            // 处理成功的响应
                            var iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);
                            parent.renderTable()
                        },
                        error: function (xhr, status, error) {
                            // 处理错误响应
                            console.error('编辑类目失败:', xhr.responseJSON);
                            // 可以在这里显示错误提示
                            layer.msg(`编辑类目失败，${xhr.responseJSON.message}`);
                        }
                    });

                    layer.msg('停止任务 ' + data.deviceName);
                }
            });
        });
    </script>
</body>

</html>